#include<bits/stdc++.h>
#define sd(n) scanf("%d",&n) 
#define sld(n) scanf("%lld",&n)
#define pd(n) printf("%d", (n))
#define pld(n) printf("%lld", n)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define fi first
#define se second
//const int N=2e5;
#define INF 0x7fffffff
typedef long long int ll;
using namespace std;
//----------------------------------------------------------------------------//
int dx[] = { -1,1,0,0 }; int dy[] = { 0,0,-1,1 };
const int N = 510;
typedef pair<int, int> PII;
int n, m, _x1_, _y1_, x2, y2;
int x_d, y_d, x_k, y_k;
char g[N][N];//存放地图
int d[N][N];//存每一个点到起点的距离
int bfs(int& sx, int& sy, int& ex, int& ey)
{

    queue <PII> q;
    q.push({ sx,sy });


    memset(d, -1, sizeof d);

    d[sx][sy] = 0;

    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        for (int i = 0; i < 4; i++) {
            int x = t.first + dx[i], y = t.second + dy[i];

            if (x >= 0 && x < n && y >= 0 && y < m && (g[x][y] == '.' || g[x][y] == 'K' || g[x][y] == 'E'||g[x][y]=='S') && d[x][y] == -1) {
                d[x][y] = d[t.first][t.second] + 1;
                q.push({ x, y });
                if (x == ex && y == ey) goto ed;
            }
        }

    }

ed:;
    return d[ex][ey];
}

int main()
{
    sd(n); sd(m);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
        {
            cin >> g[i][j];
            if (g[i][j] == 'S') _x1_ = i, _y1_ = j;
            if (g[i][j] == 'E') x2 = i, y2 = j;
            if (g[i][j] == 'D') x_d = i, y_d = j;
            if (g[i][j] == 'K') x_k = i, y_k = j;
        }
    //直接过
    int ans = bfs(_x1_, _y1_, x2, y2);
    //cout << ans << '\n';

    //找k,由于我开始有判断退出这一步,所以我这里要重新bfs,如果没有判断退出走完整张图会过于大
    int ans_k = bfs(_x1_, _y1_, x_k, y_k);
    //cout<<ans_k<<'\n';

    //更新d
    g[x_d][y_d] = 'K';
    //k找d
    int ans_d = bfs(x_k, y_k, x_d, y_d);
    //cout<<ans_d<<'\n';


    int ans_e = bfs(x_d, y_d, x2, y2);



    if (ans == -1)
    {
        if (ans_k == -1 || ans_d == -1 || ans_e == -1)
        {
            cout << -1 << '\n'; return 0;
        }
        cout << ans_k + ans_d + ans_e << '\n';
        return 0;

    }
    if (ans > 0)
    {
        if (ans_k == -1 || ans_d == -1 || ans_e == -1)
        {
            cout << ans << '\n'; return 0;
        }
        else
        {
            cout << min(ans, ans_k + ans_d + ans_e) << '\n';
            return 0;
        }
    }

    return 0;
}